import 'dart:async';

import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_news/common/api/apis.dart';
import 'package:flutter_news/common/entity/entitys.dart';
import 'package:flutter_news/common/router/router.dart';
import 'package:flutter_news/common/values/values.dart';
import 'package:flutter_news/common/widgets/widgets.dart';
import 'package:flutter_news/common/utils/utils.dart';
import 'package:flutter_news/global.dart';

@RoutePage()
class SignInPage extends StatefulWidget {
  SignInPage({Key? key}) : super(key: key);

  @override
  State<SignInPage> createState() => _SignInPageState();
}

class _SignInPageState extends State<SignInPage> {
  // email 控制器
  final TextEditingController _emailEditController = TextEditingController();

  // 密码的控制器
  final TextEditingController _pwdEditController = TextEditingController();

  // 密码的焦点控制器
  FocusNode _pwdFocusNode = FocusNode();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // 加入这句，弹出键盘的时候，视图就不会被顶起来了
      resizeToAvoidBottomInset: false,
      body: SingleChildScrollView(
        child: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          child: Center(
            child: Column(
              children: [
                _buildHeader(),
                _buildInputForm(),
                Spacer(),
                _buildThirdPartyLoginTitle(),
                SizedBox(
                  height: duSetHeight(20),
                ),
                buildThirdPartyLoginBtn(),
                SizedBox(
                  height: duSetHeight(40),
                ),
                _buildSignUpBtn(),
                SizedBox(
                  height: duSetHeight(20),
                ),
              ],
            ),
          ),
        ),
      ),
      // body: Center(
      //   child: Column(
      //     children: [
      //       _buildHeader(),
      //       _buildInputForm(),
      //       Spacer(),
      //       _buildThirdPartyLoginTitle(),
      //       SizedBox(
      //         height: duSetHeight(20),
      //       ),
      //       buildThirdPartyLoginBtn(),
      //       SizedBox(
      //         height: duSetHeight(40),
      //       ),
      //       _buildSignUpBtn(),
      //       SizedBox(
      //         height: duSetHeight(20),
      //       ),
      //     ],
      //   ),
      // ),
    );
  }

  // 跳转 注册界面
  _handleNavSignUp() {
    // Navigator.pushNamed(
    //   context,
    //   "/sign-up",
    // );

    context.router.navigate(SignUpRoute());
  }

  // 执行登录操作
  _handleSignIn() async {
    if (!duIsEmail(_emailEditController.value.text)) {
      showToast(msg: "请正确输入邮件");
      return;
    }
    if (!duCheckStringLength(_pwdEditController.value.text, 6)) {
      showToast(msg: "密码不能小于6位");
      if(_pwdFocusNode.hasFocus){
        // 失去焦点
        _pwdFocusNode.unfocus();
        //
        // closeKeyboard(context);
        // Timer(Duration(milliseconds: 3), () {
        //   _pwdFocusNode.requestFocus();
        // });
      }
      return;
    }

    UserLoginRequestEntity params = UserLoginRequestEntity(
      email: _emailEditController.value.text,
      password: duSHA256(_pwdEditController.value.text),
    );

    UserLoginResponseEntity userProfile =
        await UserAPI.login(context: context, params: params);
    Global.saveProfile(userProfile);

    // List<NewsIndexResponseEntity> newsList = await NewsAPI.index();
    // print(newsList.length);

    // Navigator.pushNamed(
    //   context,
    //   "/app",
    // );

    context.router.popAndPush(ApplicationRoute());
  }

  /// logo
  Widget _buildLogo() {
    return SizedBox(
      height: duSetWidth(76),
      width: duSetWidth(76),
      child: Stack(
        // 层叠布局，需要外面加上宽高约束，不然无法正常显示
        alignment: Alignment.center,

        children: [
          // Positioned 进行控件的定位
          Positioned(
            left: 0,
            right: 0,
            top: 0,
            bottom: 0,
            child: Container(
              decoration: BoxDecoration(
                color: AppColors.primaryBackground,
                boxShadow: [
                  Shadows.primaryShadow,
                ],
                borderRadius: BorderRadius.all(
                  Radius.circular(
                    duSetWidth(76 * 0.5),
                  ),
                ),
              ),
            ),
          ),

          Positioned(
            child: Image.asset(
              ImageNameUtil.logo,
              fit: BoxFit.none,
            ),
            top: duSetHeight(13),
          )
        ],
      ),
    );
  }

  /// 构建头部
  Widget _buildHeader() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        SizedBox(
          height: duSetHeight(84),
        ),
        _buildLogo(),
        SizedBox(
          height: duSetHeight(15),
        ),
        Text(
          "SECTOR",
          textAlign: TextAlign.center,
          style: TextStyle(
            color: AppColors.primaryText,
            fontFamily: FontFamily.montserrat,
            fontSize: duSetFontSize(24),
            fontWeight: FontWeight.w600,
            // 因为字体默认也占有一个间距，所以这里设置为 1，否则会出现字体间距
            height: 1.0,
          ),
        ),
        Text(
          "news",
          textAlign: TextAlign.center,
          style: TextStyle(
            color: AppColors.primaryText,
            fontFamily: FontFamily.avenir,
            fontWeight: FontWeight.w400,
            fontSize: duSetFontSize(16),
            height: 1.0,
          ),
          textScaleFactor: 1.0,
        ),
      ],
    );
  }

  /// 登录表单
  Widget _buildInputForm() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        SizedBox(
          height: duSetHeight(49),
        ),
        inputTextEdit(
          controller: _emailEditController,
          hintText: "Email",
          keyboardType: TextInputType.emailAddress,
          maxLen: 40,
        ),
        SizedBox(
          height: duSetHeight(15),
        ),
        inputTextEdit(
          controller: _pwdEditController,
          hintText: "Password",
          keyboardType: TextInputType.visiblePassword,
          isPassword: true,
          maxLen: 20,
          focusNode: _pwdFocusNode,
        ),
        SizedBox(
          height: duSetHeight(15),
        ),
        SizedBox(
          width: duSetWidth(295),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              btnFlatButtonWidget(
                onPressed: _handleNavSignUp,
                btnText: "Sign Up",
                bgColor: AppColors.thirdElement,
              ),
              Spacer(),
              btnFlatButtonWidget(
                onPressed: _handleSignIn,
                btnText: "Sign In",
                bgColor: AppColors.primaryElement,
              )
            ],
          ),
        ),
        TextButton(
          onPressed: () {},
          child: Text(
            "Fogot password?",
          ),
          style: ButtonStyle(
            foregroundColor: MaterialStateProperty.all(
              AppColors.secondaryElementText,
            ),
            overlayColor: MaterialStateProperty.all(
              Colors.transparent,
            ),
            textStyle: MaterialStateProperty.all(
              TextStyle(
                fontFamily: FontFamily.avenir,
                fontWeight: FontWeight.w400,
                fontSize: duSetFontSize(16),
                // 设置下行高，否则字体下沉
                height: 1,
              ),
            ),
          ),
        )
      ],
    );
  }

  /// 第三方登录标题
  Widget _buildThirdPartyLoginTitle() {
    return Text(
      "Or sign in with social networks",
      textScaleFactor: 1.0,
      textAlign: TextAlign.center,
      style: TextStyle(
        color: AppColors.primaryText,
        fontFamily: FontFamily.avenir,
        fontWeight: FontWeight.w400,
        fontSize: duSetFontSize(16),
        height: 1.0,
      ),
    );
  }

  /// 第三方登录按钮
  Widget buildThirdPartyLoginBtn() {
    return SizedBox(
      width: duSetWidth(295),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          btnFlatButtonBorderOnlyWidget(
            onPressed: () {},
            iconFileName: ImageNameUtil.iconsTwitter,
          ),
          const Spacer(),
          btnFlatButtonBorderOnlyWidget(
            onPressed: () {},
            iconFileName: ImageNameUtil.iconsGoogle,
          ),
          const Spacer(),
          btnFlatButtonBorderOnlyWidget(
            onPressed: () {},
            iconFileName: ImageNameUtil.iconsFacebook,
          ),
        ],
      ),
    );
  }

  /// 注册按钮
  Widget _buildSignUpBtn() {
    return btnFlatButtonWidget(
      onPressed: () {},
      btnText: "Sign up",
      bgColor: AppColors.secondaryElement,
      width: 294,
      fontColor: AppColors.primaryText,
      fontWeight: FontWeight.w500,
      fontSize: 16,
    );
  }
}
